package com.liit.controller.weixin;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import name.zbq.bush.receive.handler.ServletReceiveHandler;
import name.zbq.bush.receive.message.ServletReceiveMessage;
import name.zbq.bush.utils.ArrayUtil;

import org.apache.commons.codec.digest.DigestUtils;

import cn.liit.weixin.message.model.req.ReqBaseMessage;
import cn.liit.weixin.message.model.resp.RespBaseMessage;
import cn.liit.weixin.message.process.WeixinServletReceiveHandler;

@WebServlet(urlPatterns = { "/weixin/callback" })
public class WeixinServlet extends HttpServlet {
	private static final String TOKEN = "hvision";

	private static final long serialVersionUID = 357731396926143445L;
	private ServletReceiveHandler<ReqBaseMessage, RespBaseMessage> receiveHandler;

	@Override
	public void init() throws ServletException {
		super.init();
		receiveHandler = new WeixinServletReceiveHandler();
	}

	public WeixinServlet() {
		super();
	}

	/**
	 * 配置验证
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		// 验证signature 是否是微信发送过来的请求
		boolean result = checkSignature(signature, timestamp, nonce, echostr);
		if (result) {
			response.getWriter().print(echostr);
		}
	}

	/**
	 * 微信通知post次方法
	 * 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		receiveHandler.handlerMessage(new ServletReceiveMessage(request, response));
	}

	private boolean checkSignature(String signature, String timestamp, String nonce, String echostr) {
		nonce = nonce == null ? "" : nonce;
		timestamp = timestamp == null ? "" : timestamp;
		String[] tmpArr = new String[] { TOKEN, timestamp, nonce };// 临时数组
																	// 用于验证signature
		Arrays.sort(tmpArr);// 按字典序排序(默认)
		String tmpStr = ArrayUtil.join(tmpArr, "");// 拼接成字符串
		tmpStr = DigestUtils.sha1Hex(tmpStr);// 用sha1加密
		if (tmpStr.equals(signature)) {
			return true;
		}
		return false;
	}

}
